// mainPackage/pages/vipCenter/vipCenter.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    usedPoints: 0,
    levelTotal: 0,
    percentage: 0,
    chongList: [],
    vipInfo: '', //当前等级
    nextLevelScore: 0, //下一等级所需经验
    levelList: [],
    vipImg: ''
  },

  toPage(e) {
    var flag = e.currentTarget.dataset.flag;
    if (flag == 'pay') {
      var obj = e.currentTarget.dataset.obj;
      this.payHandle(obj)
    } else if (flag == 'index') {
      wx.switchTab({
        url: '/pages/index/index',
      })
    } else if (flag == 'diamond') {
      wx.navigateTo({
        url: '/mainPackage/pages/diamondMall/diamondMall',
      })
    } else if (flag == 'balance') {
      // wx.navigateTo({
      //   url: '/userPackage/pages/balanceList/balanceList',
      // })
      wx.navigateTo({
        url: '/userPackage/pages/asset/asset?nav=余额'
      })
    } else if (flag == 'info') {
      wx.navigateTo({
        url: '/userPackage/pages/userInfo/userInfo',
      })
    }

  },

  getData() {
    var url = app.globalData.url + "scVip/listVipLevelByUser",
      levelList = this.data.levelList,
      chongList = [],
      vipInfo = this.data.vipInfo,
      that = this;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {}, res => {
        console.log(res);
        if (res.flag) {
          levelList.forEach(ele => {
            ele.rules = []
            res.data.forEach(item => {
              if (item.levelId == ele.vipLevelNumber) {
                ele.rules.push(item)
              }
            })
          })
          res.data.forEach(item => {
            if (item.levelId == vipInfo.vipLevelNumber) {
              chongList.push(item)
            }
          })
          that.setData({
            chongList,
            levelList
          })
          console.log(chongList);
          console.log(levelList);
          wx.hideLoading()
        }
      },
      err => {
        console.log(err);
      })

  },
  getVip() {
    wx.showLoading({
      title: '',
    })
    var levelNum = JSON.parse(wx.getStorageSync('nextLevelScore')),
      levelTotal = 0,
      vipInfo = "";
    try {
      if (this.data.user.vipLevel < levelNum[levelNum.length - 1].vipLevelNumber) {
        levelNum.forEach(item => {
          if (this.data.user.vipLevel == item.vipLevelNumber) {
            vipInfo = item;
          }
          if (this.data.user.vipLevel < item.vipLevelNumber && this.data.user.usedPoints < item.nextScore) {
            levelTotal = item.nextScore;
            throw 1;
          }
        })
      } else {
        vipInfo = levelNum[levelNum.length - 1];
        levelTotal = levelNum[levelNum.length - 1].nextScore;
      }
    } catch (error) {
      // console.log(error);
    }


    var percentage = (Number(this.data.user.usedPoints) / Number(levelTotal)) * 100;
    if (percentage >= 100) {
      percentage = 100;
    }
    this.setData({
      nextLevelScore: levelTotal,
      percentage,
      levelList: levelNum,
      vipInfo
    })
    this.getData()
    wx.hideLoading()
    console.log(this.data.vipInfo);
  },

  // 支付
  payHandle(obj) {
    console.log(obj);
    var url = app.globalData.url + "pay/userRecharge",
      user = app.globalData.user,
      that = this;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
        userId: app.globalData.userId,
        rechargeMoney: obj.levelMoney,
        scoreNum: obj.levelScore,
        diamondNum: obj.levelDiamond,
        commissionNum: obj.giveMoney,
      }, res => {
        console.log(res);
        if (res.flag) {


          user.userScore = Number(user.userScore) + Number(obj.levelScore)
          user.diamondNum = Number(user.diamondNum) + Number(obj.levelDiamond)

          // 首次充值  userLevel 变成1   nextLevelScore 当前等级升级经验
          user.vipLevel = user.vipLevel == 0 ? 1 : user.vipLevel
          // 改变身份标识
          user.userType = user.userType == 0 ? 1 : user.userType
          wx.setStorageSync('nextLevelScore', JSON.stringify(this.data.levelList))

          app.globalData.userScore = user.userScore
          app.globalData.diamondNum = user.diamondNum
          app.globalData.user = user
          wx.setStorageSync('user', JSON.stringify(user))
          console.log(user);
          wx.showToast({
            title: '充值成功',
            icon: 'none'
          })
          that.onShow()
          return
          var datas = res.data.finalPackage;
          console.log(datas);
          wx.requestPayment({
            "timeStamp": datas.timeStamp,
            "nonceStr": datas.nonceStr,
            "package": datas.package,
            "signType": "RSA",
            "paySign": datas.paySign,
            "success": function (res) {
              console.log(res);
              if (res.errMsg == "requestPayment:ok") {
                user.userScore = Number(user.userScore) + Number(obj.levelScore)
                user.diamondNum = Number(user.diamondNum) + Number(obj.levelDiamond)
                // 首次充值  userLevel 变成1   nextLevelScore 当前等级升级经验
                user.vipLevel = user.vipLevel == 0 ? 1 : user.vipLevel
                wx.setStorageSync('nextLevelScore', this.data.nextLevelScore)
                app.globalData.userScore = user.userScore
                app.globalData.diamondNum = user.diamondNum
                app.globalData.user = user
                wx.setStorageSync('user', JSON.stringify(user))
                console.log(user);
                wx.showToast({
                  title: '充值成功',
                  icon: 'none'
                })
                that.onShow()
              }
            },
            "fail": function (res) {
              console.log(res);
              wx.showToast({
                title: '支付失败,请重试',
                icon: 'none'
              })
            },
            "complete": function (res) {
              console.log(res);
            }
          })

        } else {
          wx.hideLoading()
          wx.showToast({
            title: '支付失败,请重试',
            icon: 'none'
          })
        }
      },
      err => {
        console.log(err);
      })


  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var vipImg = '/mainPackage/image/vipCenter/vip' + JSON.parse(wx.getStorageSync('user')).vipLevel + '.png'
    this.setData({
      user: app.globalData.user,
      usedPoints: app.globalData.usedPoints,
      vipImg
    })

    this.getVip()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})